package com.woniu.service.impl;

import com.woniu.entity.*;
import com.woniu.mapper.AllMapper;
import com.woniu.service.AllService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AllServiceImpl implements AllService {

    @Resource
    private AllMapper allMapper;

    /* ---------- 1. 登录 ---------- */
    @Override
    public ResponseUtil login(String username, String password) {
        Customer c = allMapper.login(username, password);
        return c == null ? ResponseUtil.get(ResponseEnum.FAIL)
                : ResponseUtil.get(ResponseEnum.OK, c);
    }

    /* ---------- 2. 商品 ---------- */
    @Override
    public ResponseUtil listProducts(Integer categoryId, Integer page, Integer size) {
        int offset = (page - 1) * size;
        List<Product> list = allMapper.listProducts(categoryId, offset, size);
        return ResponseUtil.get(ResponseEnum.OK, list);
    }

    @Override
    public ResponseUtil getProduct(Integer productId) {
        Product p = allMapper.getProduct(productId);
        return p == null ? ResponseUtil.get(ResponseEnum.FAIL)
                : ResponseUtil.get(ResponseEnum.OK, p);
    }

    /* ---------- 3. 购物车 ---------- */
    @Override
    public ResponseUtil addCart(Cart cart) {
        return allMapper.insertCart(cart) > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil listCart(Integer customerId) {
        List<Cart> list = allMapper.listCart(customerId);
        return ResponseUtil.get(ResponseEnum.OK, list);
    }

    @Override
    public ResponseUtil deleteCart(Integer cartId) {
        return allMapper.deleteCart(cartId) > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil updateCart(Integer cartId, Integer buyNum) {
        return allMapper.updateCart(cartId, buyNum) > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    /* ---------- 4. 下单（事务） ---------- */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseUtil createOrder(Order order, List<OrderItem> items, Integer customerId) {
        String orderId = UUID.randomUUID().toString().replace("-", "");
        order.setOrderId(orderId);
        allMapper.insertOrder(order);

        // 收集本次下单的商品 ID
        List<Integer> productIds = new ArrayList<>();
        for (OrderItem i : items) {
            i.setOrderId(orderId);
            BigDecimal sumPrice = i.getPrice()
                    .multiply(BigDecimal.valueOf(i.getBuyNum()));
            i.setSumPrice(sumPrice);
            allMapper.insertOrderItem(i);

            productIds.add(i.getProductId());
        }

        // ✅ 更新购物车状态为已下单（状态 = 1）
        if (!productIds.isEmpty()) {
            allMapper.updateCartStatusToOrdered(customerId, productIds);
        }

        return ResponseUtil.get(ResponseEnum.OK, orderId);
    }


    @Override
    public ResponseUtil orderDetail(String orderId) {
        Order o = allMapper.getOrderById(orderId);
        return o == null ? ResponseUtil.get(ResponseEnum.FAIL)
                : ResponseUtil.get(ResponseEnum.OK, o);
    }

    @Override
    public ResponseUtil refundAudit(String orderId) {
        int rows = allMapper.updateOrderStatus(orderId, 6); // 6=已退款/已完成
        return rows > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseUtil confirmReceive(String orderId) {
        int rows = allMapper.receiveOrder(orderId);
        return rows > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL, "订单状态异常或已收货");
    }

    /* ---------- 5. 个人中心 ---------- */
    @Override
    public ResponseUtil getCustomer(Integer customerId) {
        Customer c = allMapper.getCustomer(customerId);
        return c == null ? ResponseUtil.get(ResponseEnum.FAIL)
                : ResponseUtil.get(ResponseEnum.OK, c);
    }

    @Override
    public ResponseUtil listOrders(Integer customerId) {
        List<Order> list = allMapper.listOrders(customerId);
        return ResponseUtil.get(ResponseEnum.OK, list);
    }


    @Override
    public ResponseUtil listAddress(Integer customerId, Integer defaultOnly) {
        List<Address> list = allMapper.listAddress(customerId, defaultOnly);
        return list.isEmpty() ? ResponseUtil.get(ResponseEnum.FAIL)
                : ResponseUtil.get(ResponseEnum.OK, list);
    }
}